package main

import (
	"context"
	"os"
	"path/filepath"

	"vov.cx/kagura/engine"
	"vov.cx/kagura/utils/app"
	"vov.cx/kagura/utils/gobuild"
)

var b = gobuild.New()

func init() {
	flags := app.OptionGroup{
		b.BuildFlagOption(),
		app.Option(func(c *app.Command) { c.Flags().BoolP("watch", "w", false, "watch hot reload") }),
	}

	root.AddCommand(
		app.New(app.Use("run [flags] [-w|--watch] <files...>"), app.Run(kaguraRun(true)), flags, app.Comment("run kagura app")),
		app.New(app.Use("build [flags] [-w|--watch] <files...>"), app.Run(kaguraRun(true)), flags, app.Comment("build kagura app")),
	)
}

func createEngine(args []string) (*engine.Engine, error) {
	src := "."
	if len(args) > 0 && args[0] != "" {
		src = args[0]
	}

	src, err := filepath.Abs(src)
	if err != nil {
		return nil, err
	}

	fi, err := os.Stat(src)
	if err != nil {
		return nil, err
	}

	if !fi.IsDir() {
		src = filepath.Dir(src)
	}

	return engine.New(src, b)
}

func kaguraRun(run bool) app.Runnable {
	return func(c *app.Command, args []string) {
		e, err := createEngine(args)
		app.CheckExit(err)

		defer func() { _ = e.Clean(context.Background()) }()

		if watch, _ := c.Flags().GetBool("watch"); watch {
			err = e.Watch(c.Context(), run)
		} else {
			err = e.Build(c.Context(), run)
		}
		app.CheckExit(err)
	}
}
